<template>
    <div>
        <div class="video-wrap" ref="player">
            <div class="video" :id="info.vid"></div>
            <div class="vip-video" v-if="(info.isVip && !vipUser && !(info.isFree || info.price)) || ((info.isFree || info.price)&&!payStatus)" >
                <div class="btn" @click="toVip($event)" v-if="!(info.isFree || info.price) && (info.isVip && !vipUser)">پەقەت VIP ئەزالا كۆرەلەيدۇ ، دەرھال ئېچىش</div>
                <div class="btn" @click="buyVideo" v-if="((info.isFree || info.price)&&!payStatus)">بۇ كىنو ھەقلىق ئىكەن ، سېتىۋالغاندىن كېيىن كۆرەلەيسىز، بۇنى بېسىپ سېتىۋېلىڭ</div>
            </div>
        </div>
        <!-- 电影购买框 -->
        <Popup height="68%" :show="buyWrapShow" :info="info" @close="showChange" @update="updateInfo"/>
        <div class="detail-wrap">
            <div class="title">
                <span>{{info.title}}</span>
            </div>
            <van-icon class="coll" :name="isLike?'star':'star-o'" @click="setLike" :color="isLike?'#ffc800':''" />
            <div class="info">
                <div class="create-time">
                    <i class="iconfont icon-lishi"></i>
                    <span class="time">
                        {{formatDate(info.create_time)}}</span>
                </div>
            </div>
        </div>
        <!-- 电视剧集结 -->
        <div class="tv" v-if="tvList.length">
            <div class="item" @click="changeTv(item)" :class="{active:(item.xh==activeTv)}" v-for="(item, index) in tvList" :key="index">{{item.xh}}</div>
        </div>
        <!-- 打赏 -->
        <Admire height="58%" :show="admireShow" :info="info" @close="admireShowChange" @update="admireUpdate"/>
        <div class="reward">
                <span class="total">
                    <i class="iconfont icon-YUAN-circle-fill hongbao"></i>
                    <span>{{admireList.length}} قېتىم</span>/
                    <span>{{TotalMoney}} يۈەن</span>
                </span>
                <span class="btn" @click="admireShow=true">تارتۇقلاش</span>
                <div class="people">
                    <span class="remind">سىزنىڭ قوللىشىڭىز، بىز ئۈچۈن مەدەت</span>
                    <div class="detail">
                        <span class="person" v-for="(item, index) in admireList" :key="index">
                            <img :src="item.userInfo.headimgurl" alt="">
                            <span class="name">{{item.userInfo.nickname.slice(0,3)}}</span>
                        </span>
                    </div>
                </div>
            </div>
        <!-- 推荐电影 -->
        <div class="recommend">
            <span class="bar"></span>
            <span class="txt">تەۋسىيە</span>
        </div>
        <div class="recommend-wrap">
            <!-- <div class="list">
                <VideoCover :show="true" v-for="item in recommendList" :key="item.vid" :info="item"></VideoCover>
            </div> -->
            <waterfall :col="3" :data="recommendList">
                <template>
                    <VideoCover v-for="(item, index) in recommendList" :key="index" :info="item" />
                </template>
            </waterfall>
        </div>
    </div>
</template>
<script>
import VideoCover from "@/components/VideoCover.vue";
import { formatDate, shareFrend, shareMoments , getQueryVariable} from "@/utils";
import Popup from './Popup'
import Admire from './Admire'
import { Toast, Dialog } from 'vant'
export default {
    name: "Player",
    components: {
        VideoCover,
        Popup,
        Admire
    },
    data() {
        return {
            buyWrapShow :false,
            admireShow:false,
            info: {},
            recommendList: [],
            tvList: [],
            activeTv: 1,
            player: null, 
            isLike: 0,
            payStatus: 0,
            admireList: [],
            playFlag: false  //播放加锁
        };
    },
    mounted() {
        this.getVideoInfo();
        this.getRecommendList();
        this.getAdmireList();
    },
    methods: {
        formatDate,
        initInfo() {
            if(!this.vipUser) {
                this.playFlag = false
            } else this.playFlag = true
            this.$nextTick(() => {
                let el = document.getElementById(this.info.vid);
                this.player = new Player({
                    el,
                    url: this.info.videoUrl,
                    // url :'http://h5player.bytedance.com/video/mp4/xgplayer-demo-720p.mp4',
                    // width: el.parentElement.style.width,
                    // height: el.parentElement.style.height
                    fluid: true,
                    poster: this.info.coverImg,
                    playbackRate: [0.5, 0.75, 1, 1.5, 2],//快速播放
                    // 'x5-video-player-type': 'h5',
                    // 'x5-video-player-fullscreen': false

                });
                let self = this;
                this.player.on('play', function (e) {
                    if(!self.playFlag) {
                        this.pause();
                        Dialog({
                                title:'ئەسكەرتىش',
                                message:'كىوخانىمىزنى چەمبىرەككە يوللىغاندىن كېيىن داۋاملىق كۆرەلەيسىز',
                                showCancelButton:false,
                                confirmButtonText:'ماقۇل'
                        })
                    }
                })
            });
        },
        getVideoInfo() {
            let self = this;
            let vid,type;
            vid = getQueryVariable(window.location.href).vid;
            type = getQueryVariable(window.location.href).type;
            vid = vid ? vid : this.$route.query.vid;
            type = type!=undefined ? type : this.$route.query.type;
            // let { vid, type } = this.$route.query;
            if (type != 0 && type != 1 && !vid) {
                this.$router.push("/home");
            }
            this.$http
                .post("/getVideoInfo", {
                    vid,
                    type
                })
                .then(res => {
                    try {
                        this.info = JSON.parse(this.$decrypt(res));
                        // 如果是付费电影
                        if( this.info.price ){
                            this.getUserPayStatus();
                        }
                        this.initInfo();
                        this.getCollectStatus();
                        this.initShare();
                        if (type == 1) {
                            this.tvList = JSON.parse(this.info.qisim);
                            this.$nextTick(() => {
                                this.player.destroy();
                                let el = document.getElementById(this.info.vid);
                                this.player = new Player({
                                    el,
                                    url: self.tvList[0].url,
                                    // url :'http://h5player.bytedance.com/video/mp4/xgplayer-demo-720p.mp4',
                                    // width: el.parentElement.style.width,
                                    // height: el.parentElement.style.height
                                    fluid: true,
                                    poster: self.info.coverImg,
                                    playbackRate: [0.5, 0.75, 1, 1.5, 2],//快速播放

                                });
                                this.player.on('play', function (e) {
                                    if(!self.playFlag) {
                                        this.pause();
                                        Dialog({
                                                title:'ئەسكەرتىش',
                                                message:'كىوخانىمىزنى چەمبىرەككە يوللىغاندىن كېيىن داۋاملىق كۆرەلەيسىز',
                                                showCancelButton:false,
                                                confirmButtonText:'ماقۇل'
                                        })
                                    }
                                })
                                /* this.player.on('timeupdate', function (e) {
                                    if (e.currentTime >= 180 && !self.playFlag) {
                                        this.pause();
                                        this.exitFullscreen(el);
                                        exitScreen();
                                        Dialog({
                                            title:'ئەسكەرتىش',
                                            message:'كىوخانىمىزنى چەمبىرەككە يوللىغاندىن كېيىن داۋاملىق كۆرەلەيسىز',
                                            showCancelButton:false,
                                            confirmButtonText:'ماقۇل'
                                            })
                                    }
                                }); */
                            })
                        }
                    } catch (error) {}
                })
                .catch(err => {
                    this.$toast(err);
                });
        },
        getRecommendList() {
            try {
                let vid,type,sort;
                vid = getQueryVariable(window.location.href).vid;
                type = getQueryVariable(window.location.href).type;
                sort = getQueryVariable(window.location.href).sort;
                vid = vid ? vid : this.$route.query.vid;
                type = type!=undefined ? type : this.$route.query.type;
                sort = sort ? sort : this.$route.query.sort;
                if (type == undefined) {
                    this.$router.push("/home");
                    return;
                } else {
                    this.$http
                        .post("/getVideo", {
                            from: "recommend",
                            sort
                        })
                        .then(res => {
                            let list = res.list;
                            this.recommendList = list;
                        });
                }
            } catch (error) {
                
            }
        },
        changeTv(item) {
            if(!this.vipUser) {
                this.playFlag = false
            } else this.playFlag = true
            this.activeTv = item.xh;
            this.player.destroy();
            this.$nextTick(() => {
                let el = document.getElementById(this.info.vid);
                this.player = new Player({
                    el,
                    url: item.url,
                    fluid: true,
                    poster: this.info.coverImg
                });
                let self = this;
                this.player.on('play', function (e) {
                    if(!self.playFlag) {
                        this.pause();
                        Dialog({
                                title:'ئەسكەرتىش',
                                message:'كىوخانىمىزنى چەمبىرەككە يوللىغاندىن كېيىن داۋاملىق كۆرەلەيسىز',
                                showCancelButton:false,
                                confirmButtonText:'ماقۇل'
                        })
                    }
                })
            });
        },
        initShare() {
            let self = this;
            let option = {
                title: self.info.title, // 分享标题
                desc: "بۇيەرنى بېسىپ كۆرۈڭ", // 分享描述
                // link: `http://v.qolayapp.cn/#/player?vid=${self.info.vid}&type=${self.info.type}&sort=${self.info.sort}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                link: window.location.href,
                imgUrl: self.info.coverImg, // 分享图标
                success: function() {
                    // 设置成功
                }
            };
            shareFrend(this, option);
             this.$nextTick(() => {
                wx.ready(function () {
                    //需在用户可能点击分享按钮前就先调用 {
                    wx.onMenuShareTimeline({
                        title: self.info.title, // 分享标题
                        desc: "بۇيەرنى بېسىپ كۆرۈڭ", // 分享描述
                        link: `http://v.qolayapp.cn/#/player?vid=${self.info.vid}&type=${self.info.type}&sort=${self.info.sort}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: self.info.coverImg, // 分享图标
                        success: function () {
                            _hmt.push(['_trackEvent', 'share', 'click','player']);
                            Toast({message:'ھەمبەھىرلىگىنىڭىزگە رەھمەت',duration: 1500});
                            self.playFlag = true;
                        }
                    })
                });
            });
        },
        getCollectStatus(){
            this.$http.get('/getCollectVideo',{params:{vid:this.info.vid,from:'status'}}).then(res=>{
                this.isLike = res;
            }).catch(err=>{
                this.isLike = 0;
            })
        },
        setLike(){
            this.$http.post('/setVideoCollect',{vid:this.info.vid,status:Number(!this.isLike)}).then( res =>{
                this.isLike = !this.isLike;
            })
        },
        toVip(e){
            e.stopPropagation();
            this.$router.push('/vip')
        },
        buyVideo(){
            this.buyWrapShow = true
        },
        showChange(val){
            this.buyWrapShow = val;
        },
        admireShowChange(val){
            this.admireShow = val;
        },
        getUserPayStatus(){
            try {
                let openId = this.$store.state.userInfo ? this.$store.state.userInfo.openid: JSON.parse(window.localStorage.getItem('userInfo')).openid;
                this.$http.get('/getVideoPayStatus',{ params: {
                    openId,
                    vid:this.info.vid
                }}).then( res =>{
                    let result = JSON.parse(this.$decrypt(res));
                    
                    this.payStatus = Number(result.status);
                })
            } catch (error) {
            }
        },
        updateInfo(){
            this.getUserPayStatus();
            this.buyWrapShow = false;
        },
        admireUpdate(){
            this.getAdmireList();
        },
        async getAdmireList(){
            try {
                let vid,type;
                vid = getQueryVariable(window.location.href).vid;
                vid = vid ? vid : this.$route.query.vid;
                let info = await this.$http.get('/getAdmire',{params:{vid}});
                info = JSON.parse(this.$decrypt(info));
                if(info.length) {
                    info = info.map(item => {
                        return {...item,userInfo:JSON.parse(item.user_info)}
                    });
                this.admireList = info;
                }
                
            } catch (error) {
            }
        },
        // 退出全屏
        exitScreen() {  
                console.log('执行全屏退出')
                // let video = document.querySelector('video');
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if(document.oRequestFullscreen){
                    document.oCancelFullScreen();
                } else if (document.webkitExitFullscreen){
                    document.webkitExitFullscreen();
                }
                 else if (video.webkitExitFullScreen) {
                    video.webkitExitFullScreen();
                } else if (video.webkitEnterFullscreen) {
                    video.webkitEnterFullscreen();
                } else if (video.exitFullscreen) {
                    video.exitFullscreen();
                } else if(video.oRequestFullscreen){
                    video.oCancelFullScreen();
                } else if (video.mozCancelFullScreen) {
                    video.mozCancelFullScreen();
                } else if (video.webkitCancelFullScreen) {
                    video.webkitCancelFullScreen();
                } else if (video.msExitFullscreen) {
                    video.msExitFullscreen();
                } else {
                    console.log('这些都没有')
                }
        }
    },
    watch: {
        "$route.query"(newVal, oldVal) {
            if (newVal.vid != oldVal.vid) {
                this.playFlag = false;
                this.player.destroy()
                this.getVideoInfo();
                this.getRecommendList();
            }
        }
    },
    computed: {
        vipUser() {
            return this.$store.state.userInfo ? Number(this.$store.state.userInfo.isVip) :false
        },
        TotalMoney() {
            return Math.round(this.admireList.reduce((total, curr) => total + curr.money, 0)/100);
        }
    }
};
</script>

<style lang="scss" scoped>
%flexCenter{
    display: flex;
    justify-content: center;
    align-items: center;
}
.video-wrap {
    width: 100vw;
    height: 400px;
    position: relative;
    .vip-video{
        position: absolute;
        width: 100%;
        height: 105%;
        left: 0;
        top: 0;
        background-color: rgba(0, 0, 0, 0.65);
        z-index: 130;
        pointer-events: all;
        .btn{
            font-size: 26px;
            margin: 0 auto;
            margin-top: 270px;
            width: 60%;
            padding: 20px 6px;
            border-radius: 30px;
            background-color: #19a04c;
            color: #fff;
            direction: rtl;
            @extend %flexCenter;
        }
    }
}
.detail-wrap {
    min-height: 100px;
    width: 98%;
    box-shadow: 0 0 10px 2px rgba(0, 0, 0, 0.15);
    border-radius: 20px;
    margin: 15px auto 15px;
    margin-top: 30px;
    position: relative;
    .title {
        line-height: 40px;
        color: #888;
        padding-top: 12px;
        padding-left: 25px;
        font-size: 34px;
        transform: scaleY(0.78);
        text-align: left;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
        .coll {
            font-size: 40px; 
            position: absolute;
            top: 10%;
            right: 3%;
            border-radius: 50%;
            background-color: rgba(0,162,255,0.74);
            height: 80px;
            width: 80px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
        }
    .info {
        height: 42px;
        color: #888;
        font-size: 32px;
        padding-left: 10px;
        i {
            display: inline-block;
            font-size: 28px;
        }
        .create-time {
            float: left;
            ::after {
                content: "";
                display: block;
                clear: both;
            }
            .time {
                font-size: 27px;
            }
        }
        .views {
            padding-right: 20px;
            float: right;
            span {
                display: inline-block;
            }
            i {
                margin-left: 15px;
            }
            .view-time {
                margin-left: 15px;
            }
            .collect {
                font-size: 32px;
                margin-right: 15px;
            }
            .like {
                margin-left: 10px;
            }
        }
    }
}
.share {
    height: 180px;
    width: 98%;
    box-shadow: 0 0 15px 2px rgba(0, 0, 0, 0.15);
    border-radius: 20px;
    margin: 0 auto 10px;
    color: #333333;
    .title {
        text-align: center;
        font-size: 28px;
        height: 30px;
        padding: 8px 0;
    }
    .imgs {
        width: 80%;
        margin: 0 auto;
        display: flex;
        justify-content: space-around;
        flex-direction: row;
        .item {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            text-align: center;
            margin-left: 50px;
            img {
                width: 80px;
                height: 80px;
            }
            button {
                display: none;
            }
        }
    }
}
.tv {
    width: 96%;
    box-shadow: 0 0 15px 2px rgba(0, 0, 0, 0.15);
    border-radius: 20px;
    margin: 0 auto 10px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 15px 10px;
    &::after {
        content: "";
        flex: auto;
    }
    .item {
        width: 55px;
        height: 55px;
        border-radius: 50%;
        background-color: rgb(44, 149, 219);
        @extend %flexCenter;
        margin: 10px 1%;
        color: #fff;
    }
    .active {
        color: #fff;
        background-color: #50b674;
    }
}
.recommend {
    height: 50px;
    width: 98%;
    margin: 0 auto;
    box-shadow: 0 0 15px 2px rgba(0, 0, 0, 0.15);
    border-radius: 10px;
    text-align: left;
    margin-bottom: 10px;
    .bar {
        height: 36px;
        display: inline-block;
        width: 10px;
        background-color: #f40;
        margin-top: 8px;
        margin-left: 10px;
        border-radius: 5px;
        margin-right: 15px;
    }
    .txt {
        font-size: 30px;
        color: #f40;
        vertical-align: middle;
        display: inline-block;
        margin-bottom: 17px;
    }
}
.recommend-wrap {
    // width: 100%;
    box-shadow: 0 0 15px 2px rgba(0, 0, 0, 0.15);
    border-radius: 10px;
    padding: 0 1.5vw;
    .list {
        display: grid;
        grid-template-columns: 48% 48%;
        grid-column-gap: 15px;
        /deep/.title {
            color: #333333;
        }
    }
}
.reward {
        width: 98%;
        box-shadow: 0 0 15px 2px rgba(0, 0, 0, 0.15);
        border-radius: 20px;
        margin: 0 auto 10px;
        .btn {
            height: 60px;
            width: 200px;
            display: inline-block;
            background-image: linear-gradient(to right, #ee0979, #ff6a00);
            border-radius: 46px;
            text-align: center;
            font-size: 25px;
            line-height: 70px;
            color: #fafafa;
            margin-left: 25px;
            margin-top: 20px;
            opacity: 0.9;
        }
        .total {
            display: inline-block;
            padding-top: 12px;
            padding-left: 15px;
            font-size: 28px;
            i,
            span {
                display: inline-block;
                font-size: 28px;
                color: #888;
            }
            .hongbao {
                color: #f50;
                margin-right: 6px;
                font-size: 34px;
            }
        }
        .people {
            text-align: center;
            padding-top: 15px;
            padding-bottom: 18px;
            .remind {
                color: #f40;
                direction: rtl;
                font-size: 30px;
            }
            .detail {
                display: flex;
                justify-content: center;
                flex-wrap: wrap;
               /*  &::after {
                    content: "";
                    width: 12%; 
                    display: block; 
                    height:0; 
                } */
                .person {
                    display: inline-flex;
                    justify-content: center;
                    flex-direction: column;
                    align-items: center;
                    width: 14%;
                    img {
                        width: 60px;
                        height: 60px;
                        border-radius: 50%;
                        display: inline-block;
                        margin: 5px 0 5px 0;
                    }
                    .name {
                        font-size: 20px;
                        overflow: hidden;
                        text-overflow: clip;
                        white-space: nowrap;
                        color: #123;
                    }
                }
            }
        }
    }
</style>